package com.daigou.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.daigou.dao.OrderMapper;
import com.daigou.dto.OrderQuery;
import com.daigou.dto.PageInfo;
import com.daigou.dto.ServiceResult;
import com.daigou.model.Customer;
import com.daigou.model.Order;
import com.daigou.model.Product;
import com.daigou.model.ShopCustomer;
import com.daigou.model.User;
import com.daigou.service.CustomerService;
import com.daigou.service.OrderService;
import com.daigou.service.PayService;
import com.daigou.service.ProductService;
import com.daigou.service.UserService;
import com.daigou.tools.GenerateUUID;
import com.daigou.tools.SendMobileMessageUtils;

/**  
 * @Title: OrderServiceImpl.java
 * @Package com.daigou.service
 * @Description: TODO
 * @author lizhi
 * @date 2018年3月27日
 */
@Service("orderService")  
public class OrderServiceImpl implements OrderService {
	private static final Logger LOGGER = LoggerFactory.getLogger(OrderServiceImpl.class);
	@Autowired  
	protected OrderMapper orderMapper;
	
	@Autowired  
	protected CustomerService customerService;
	
	@Autowired  
	protected PayService payService;
	
	@Autowired  
	protected ProductService productService;
	
	@Autowired
	private UserService userService;
	
	/**
	 * 下单，前后端统一用一个
	 */
	public ServiceResult insertOrUpdate(Order order) throws Exception{
		boolean isAdd = false;
		if(order.getId() == null){
			isAdd = true;
			if(order.getDr() == 1 && order.getBuyerCode() != null){
				BigDecimal orderAmount = order.getPrice().multiply(order.getNum());
				order.setOrderAmount(orderAmount);
				ShopCustomer shopCustomer = customerService.selectByShopIdAndMobile(order.getShopId(), Long.parseLong(order.getBuyerCode()));
				if(shopCustomer != null){
					orderAmount = orderAmount
							.multiply(new BigDecimal(shopCustomer.getCustomerDiscount()))
							.divide(new BigDecimal(100)).setScale(2, RoundingMode.HALF_UP);
				}
				order.setTotalAmount(orderAmount);
			}
			order.setTs(System.currentTimeMillis());
			//算总额
			//如果是新增，状态为已支付
			if(order.getPayStatus() == 2){
				order.setPayAmount(order.getTotalAmount());
				order.setNoPayAmount(BigDecimal.ZERO);
			}else{
				order.setNoPayAmount(order.getTotalAmount());
			}
			if(order.getProductId() == null || "".equals(order.getProductId())){
				Product product = new Product();
				product.setName(order.getProductName());
				product.setSalePrice(order.getPrice());
				product.setMarketPrice(order.getPrice());
				product.setCate(order.getCate());
				product.setBrand(order.getBrand());
				product.setProductionPlace(order.getProductionPlace());
				product.setSpec(order.getSpec());
				product.setPicMain(order.getPicMain());
				product.setShopId(order.getShopId());
				product.setCreatedTime(new Date());
				product.setCreatorId(order.getCreatorId());
				//1上架
				product.setStatus(1);
				//0，草稿
				product.setDr(0);
				ServiceResult result = productService.insertOrUpdate(product);
				order.setProductId(Long.parseLong(result.getData().toString()));
			}
			order.setId(GenerateUUID.generateUUID());
			
			orderMapper.insertSelective(order);
		}else{
			if(order.getDr() == 1){
				BigDecimal orderAmount = order.getPrice().multiply(order.getNum());
				order.setOrderAmount(orderAmount);
				orderAmount = orderAmount
						.multiply(new BigDecimal(order.getCustomerDiscount()))
						.divide(new BigDecimal(100)).setScale(2, RoundingMode.HALF_UP);
				order.setTotalAmount(orderAmount);
			}
			order.setNewTs(System.currentTimeMillis());
			order.setModifiedTime(new Date());
			order.setModifierId(order.getCreatorId());
			//修改时，不要改创建时间
			order.setCreatedTime(null);
			order.setCreatorId(null);
			//order.setTotalAmount(orderAmount);
			BigDecimal payAmount = payService.selectPayAmountByOrderId(order.getShopId(), order.getId());
			if(payAmount == null || payAmount.compareTo(BigDecimal.ZERO) == 0){
				//如果是编辑，状态为已支付
				if(order.getPayStatus() == 2){
					order.setPayAmount(order.getTotalAmount());
					order.setNoPayAmount(BigDecimal.ZERO);
				}else{
					order.setNoPayAmount(order.getTotalAmount());
				}
			}else{
				if(payAmount.compareTo(order.getTotalAmount()) >= 0){
					//已支付
					order.setPayStatus(2);
					order.setPayAmount(order.getTotalAmount());
					order.setNoPayAmount(BigDecimal.ZERO);
				}else{
					//支付中
					order.setPayStatus(1);
					order.setPayAmount(payAmount);
					if(order.getTotalAmount().compareTo(payAmount) < 0){
						order.setNoPayAmount(BigDecimal.ZERO);
					}else{
						order.setNoPayAmount(order.getTotalAmount().subtract(payAmount));
					}
				}
			}
			
			int result = orderMapper.updateByPrimaryKeySelective(order);
			if(result == 0){
				throw new Exception("订单已过期,请刷新后重试!");
			}
		}
		if(order.getBuyerCode() != null && !"".equals(order.getBuyerCode().trim())){
			ShopCustomer customer = new ShopCustomer();
			customer.setShopId(order.getShopId());
			customer.setLoginName(order.getBuyerCode());
			customer.setMobile(Long.parseLong(order.getBuyerCode()));
			customer.setCustomerName(order.getBuyerName());
			customer.setLinkName(order.getBuyerName());
			customer.setWeixin(order.getBuyerWeixin());
			customer.setAddress(order.getAddress());
			customer.setEmail(order.getEmail());
			customer.setCustomerDiscount(order.getCustomerDiscount());
			customer.setCustomerLevel(0);
			customer.setCreatorId(order.getCreatorId());
			customer.setCreatedTime(new Date());
			ServiceResult customerResult = customerService.insertOrUpdate(customer);
			LOGGER.info("订单保存用户信息结果:"+customerResult.getMessage());
			//给会员发短信
			if(isAdd){
				String templateParamCustomer = "{\"shopName\":\""+order.getShopName()+"\"}";
				SendMobileMessageUtils.sendSms(order.getBuyerCode(), SendMobileMessageUtils.TEMP_CODE_CUSTOMER_NOTIFY,templateParamCustomer);
			}
		}
		if(isAdd){
			//emailSendSeOrvice.sendMailByVelocity(order.getEmail(),order,EmailTypeEnum.INFORM.getType());
			//给店主发短信
			StringBuilder templateParamManager = new StringBuilder();
			templateParamManager.append("{\"shopName\":\"").append(order.getShopName()).append("\",");
			templateParamManager.append("\"consignee\":\"").append(order.getBuyerName()).append("\",");
			templateParamManager.append("\"number\":\"").append(order.getBuyerCode()).append("\"}");
			User adminUser = userService.selectAdminUser(order.getShopId());
			if(adminUser != null){
				SendMobileMessageUtils.sendSms(adminUser.getLoginName(), 
						SendMobileMessageUtils.TEMP_CODE_MANAGER_NOTIFY,
						templateParamManager.toString());
			}
			//给业务员发短信
			if(order.getCreatorId() != null && !Customer.NO_BUSINESS.equals(order.getCreatorId())){
				User managerUser = userService.selectByPrimaryKey(order.getCreatorId());
				if(managerUser != null){
					SendMobileMessageUtils.sendSms(managerUser.getLoginName(), 
							SendMobileMessageUtils.TEMP_CODE_MANAGER_NOTIFY,
							templateParamManager.toString());
				}
			}
		}
		return new ServiceResult(true,"订单保存成功!",order.getId());
	}
	
	public int deleteByPrimaryKey(Long id){
		return orderMapper.deleteByPrimaryKey(id);
	}

	public int insert(Order record){
		return orderMapper.insert(record);
	}

	public int insertSelective(Order record){
		record.setId(GenerateUUID.generateUUID());
		return orderMapper.insertSelective(record);
	}
	
	public PageInfo<Order> selectByCondition(OrderQuery orderQuery){
		List<Order> orderList = orderMapper.selectByCondition(orderQuery);
		for(Order order:orderList){
			order.setStatusName(order.getStatus());
			order.setPayStatusName(order.getPayStatus());
		}
		PageInfo<Order> pageInfo = new PageInfo<Order>();
		pageInfo.setRows(orderList);
		return pageInfo;
	}
	/**
	 * 查询草稿状态的order
	 * @param shopId
	 * @param searchKey
	 * @return
	 */
	public List<Order> selectCaogaoByShopId(Long shopId,String searchKey){
		Map<String,Object> paramMap = new HashMap<String,Object>();
		paramMap.put("shopId", shopId);
		paramMap.put("searchKey", searchKey);
		List<Order> orderList =  orderMapper.selectCaogaoByShopId(paramMap);
		for(Order order:orderList){
			order.setStatusName(order.getStatus());
			order.setPayStatusName(order.getPayStatus());
		}
		return orderList;
	}
	public Integer selectTotalCaogaoByShopId(Long shopId,String searchKey){
		Map<String,Object> paramMap = new HashMap<String,Object>();
		paramMap.put("shopId", shopId);
		paramMap.put("searchKey", searchKey);
		return orderMapper.selectTotalCaogaoByShopId(paramMap);
	}
	public Integer selectTotalCountByCondition(OrderQuery orderQuery){
		return orderMapper.selectTotalCountByCondition(orderQuery);
	}
	public BigDecimal selectTotalAmountByCondition(OrderQuery orderQuery){
		return orderMapper.selectTotalAmountByCondition(orderQuery);
	}
	
	public BigDecimal selectPayAmountByCondition(OrderQuery orderQuery){
		return orderMapper.selectPayAmountByCondition(orderQuery);
	}
	public BigDecimal selectNoPayAmountByCondition(OrderQuery orderQuery){
		return orderMapper.selectNoPayAmountByCondition(orderQuery);
	}
	public Order selectByPrimaryKey(Long id){
		Order order = orderMapper.selectByPrimaryKey(id);
		order.setStatusName(order.getStatus());
		order.setPayStatusName(order.getPayStatus());
		return order;
	}

	public int updateByPrimaryKeySelective(Order record){
		record.setNewTs(System.currentTimeMillis());
		return orderMapper.updateByPrimaryKeySelective(record);
	}

	public int updateByPrimaryKey(Order record){
		return orderMapper.updateByPrimaryKey(record);
	}
	/**
	 * 更新订单那支付金额
	 * @param orderId
	 * @param payAmount
	 * @return
	 */
	public int updatePayAmountByPrimaryKey(Order record){
		return orderMapper.updatePayAmountByPrimaryKey(record);
	}
	
	/**
	 * 为首页写的订单列表
	 * 过滤所有新建和支付中的订单
	 * @param orderQuery
	 * @return
	 */
	public List<Order> selectOrder4IndexByCondition(OrderQuery orderQuery){
		List<Order> orderList = orderMapper.selectOrder4IndexByCondition(orderQuery);
		for(Order order:orderList){
			order.setStatusName(order.getStatus());
			//order.setPayStatusName(order.getPayStatus());
		}
		return orderList;
	}
	/**
	 * 为报表写的订单数量
	 * @param qrderQuery
	 * @return
	 */
	public int selectOrderCount4ReportByCondition(OrderQuery qrderQuery){
		return orderMapper.selectOrderCount4ReportByCondition(qrderQuery);
	}
	/**
	 * 为报表写的订单总额
	 * @param qrderQuery
	 * @return
	 */
	public Order selectOrder4ReportByCondition(OrderQuery qrderQuery){
		return orderMapper.selectOrder4ReportByCondition(qrderQuery);
	}
}  